﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.Drawing;

namespace WpfPdfReader
{
    public class ImageSourceHelper
    {
        public static ImageSource ImageToSource(System.Drawing.Image image)
        {
            if (image == null)
                return null;
            using (MemoryStream imgStream = new MemoryStream())
            {
                image.Save(imgStream, System.Drawing.Imaging.ImageFormat.Png);
                ImageSource imgsrc = BytesToBitmapImage(imgStream.ToArray());
                return imgsrc;
            }
        }

        public static System.Drawing.Image SourceToImage(ImageSource imageSource)
        {
            byte[] imageBytes = BitmapImageToBytes(imageSource);
            return ImageHelper.ReadImage(imageBytes);
        }

        public static System.Drawing.Image SourceToImage(Stream streamSource)
        {
            if (streamSource != null)
            {
                Image img = Image.FromStream(streamSource);
                return img;
            }
            else
                return null;
        }

        public static byte[] BitmapImageToBytes(ImageSource imageSource)
        {
            BitmapImage bmp = imageSource as BitmapImage;
            byte[] byteArray = null;
            try
            {
                Stream sMarket = bmp.StreamSource;
                if (sMarket != null && sMarket.Length > 0)
                {
                    sMarket.Position = 0;
                    BinaryReader br = new BinaryReader(sMarket);
                    byteArray = new byte[sMarket.Length];
                    int i = br.Read(byteArray, 0, byteArray.Length);
                    //MemoryStream ms = sMarket as MemoryStream;
                    //byteArray = ms.ToArray();
                }
                else
                {
                    Uri url = bmp.UriSource;
                    System.Drawing.Image image = System.Drawing.Image.FromFile(url.LocalPath);
                    //image.Save(@"d:\test.jpg");
                    byteArray = ImageHelper.ImageToBytes(image);
                }
            }
            catch
            {
                //other exception handling 
            }
            return byteArray;
        }

        public static BitmapImage BytesToBitmapImage(byte[] byteArray)
        {
            BitmapImage bmp = null;
            try
            {
                bmp = new BitmapImage();
                bmp.BeginInit();
                bmp.StreamSource = new MemoryStream(byteArray);
                bmp.EndInit();
            }
            catch
            {
                bmp = null;
            }
            return bmp;
        }
    }
}
